package com.zpz.framework.zpzoauth.common.encrypt;


import java.io.ByteArrayOutputStream;
import java.util.zip.Deflater;
import java.util.zip.Inflater;

/*
* @author zhangpanzhi
* @date 2019-03-19
* */
public class ZipUtil {
    /**
     * zlib解压
     *
     * @param input
     * @return
     */
    public static byte[] unzip(byte[] input) throws Exception {
        if (input == null || input.length == 0) {
            return input;
        }

        byte[] out = null;
        ByteArrayOutputStream bao = null;
        Inflater decompresser = new Inflater();
        try {
            bao = new ByteArrayOutputStream(input.length);
            decompresser.setInput(input);
            byte[] buf = new byte[1024];
            int len = 0;
            while (!(decompresser.finished() || decompresser.needsInput())) {
                len = decompresser.inflate(buf);
                if (len == 0) {
                    break;
                }
                bao.write(buf, 0, len);
            }
            out = bao.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("ILLEGAL_COMPRESSION");
        } finally {
            if (null != bao) {
                bao.close();
            }
            decompresser.end();
        }
        return out;

    }

    /**
     * zlib压缩
     *
     * @param input
     * @return
     */
    public static byte[] zip(byte[] input) throws Exception {
        if (input == null || input.length == 0) {
            return input;
        }

        byte[] out = null;
        ByteArrayOutputStream bao = null;
        Deflater compresser = new Deflater();
        try {
            compresser.setInput(input);
            compresser.finish();
            bao = new ByteArrayOutputStream(input.length);
            byte[] buf = new byte[1024];
            int len;
            while (!compresser.finished()) {
                len = compresser.deflate(buf);
                bao.write(buf, 0, len);
            }
            out = bao.toByteArray();
        } finally {
            if (null != bao) {
                bao.close();
            }
            compresser.end();
        }
        return out;
    }
}
